package com.lazyframework.generator.service.impl;

import com.lazyframework.generator.core.DBTypeMappings;
import com.lazyframework.generator.service.SchemaService;
import com.lazyframework.generator.mapper.SchemaMapper;
import com.lazyframework.generator.model.Column;
import com.lazyframework.generator.model.Table;
import com.lazyframework.generator.model.Schema;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * describes
 *
 * @author lazy
 */
@Service
public class SchemaServiceImpl implements SchemaService {

    private final SchemaMapper schemaMapper;

    public SchemaServiceImpl(SchemaMapper schemaMapper) {
        this.schemaMapper = schemaMapper;
    }

    @Override
    public List<Schema> schemas() {
        return schemaMapper.schemas();
    }

    @Override
    public List<Table> tables(String schema) {
        return schemaMapper.tables(schema);
    }

    @Override
    public List<Column> columns(String table, String schema) {
        List<Column> columns = schemaMapper.columns(table, schema);
        // JDBCType 转 JavaType
        columns.forEach(column -> {
            String jdbcType = column.getType();
            String javaType = DBTypeMappings.getJavaType(jdbcType.toUpperCase());
            column.setJavaType(javaType != null ? javaType : "Object");
        });
        // 驼峰转下划线
        columns.forEach(column -> column.setProperty(this.getPropertyName(column.getName())));
        return columns;
    }

    @Override
    public Table getTableInfo(String table, String schema) {
        Table tableInfo = schemaMapper.findTable(table, schema);
        tableInfo.setColumns(columns(table, schema));
        return tableInfo;
    }

    /**
     * 驼峰转下划线
     *
     * @param columnName 数据库字段名
     * @return Java Property名
     */
    private String getPropertyName(String columnName) {
        String[] ary = columnName.split("_");
        if (ary.length == 1) {
            return columnName.toLowerCase();
        }
        StringBuilder property = new StringBuilder();
        for (int i = 0; i < ary.length; i++) {
            String c = ary[i];
            if (i == 0) {
                property.append(c.toLowerCase());
            } else {
                property.append(c.substring(0, 1).toUpperCase()).append(c.substring(1).toLowerCase());
            }
        }
        return property.toString();
    }

}
